<?php

namespace app\admin\controller\api;

use app\common\model;

/**
 * 园区
 * @internal
 */
class Garden extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 根据园区id获取楼栋列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buildings()
    {
        $id = $this->request->request('id');
        $type = $this->request->request('type', 0);
        $result = model\Building::where('garden_id', $id)
            ->where(function ($query) use ($type) {
                if ($type) {
                    $query->whereIn('type', [$type, 3]);
                }
            })
            ->field('id,number,name')->select();

        $this->success('', $result);
    }

    /**
     * 根据学校id、园区number 获取楼栋列表
     * @User ZhenZiHan
     * @Date 2019/12/23
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buildingsByNumber()
    {
        $school_id = $this->request->request('school_id');
        $garden_number = $this->request->request('garden_number');
        $type = $this->request->request('type', 0);

        $school_ids = $this->getSchoolIds($this->_user['id']);

        $result = model\Building::alias('building')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id')
            ->where('garden.school_id', $school_id)
            ->where('garden.number', $garden_number)
            ->where(function ($query) use ($type, $school_ids) {
                if ($type) {
                    $query->whereIn('building.type', [$type, 3]);
                }
                if (!in_array('*', $school_ids)) {
                    $query->whereIn('building.school_id', $school_ids);
                }
            })
            ->field('building.id,building.number,building.name')
            ->select();

        $this->success('', $result);

    }

}